<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
        <el-form-item label="医生姓名">
          <el-input v-model="queryParams.name" placeholder="请输入医生姓名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <el-button type="primary" @click="handleAdd">新增医生</el-button>
      </template>

      <el-table v-loading="loading" :data="doctorList">
        <el-table-column label="医生姓名" prop="realName" />
        <el-table-column label="专长" prop="specialty" show-overflow-tooltip />
        <el-table-column label="认证状态" align="center">
          <template #default="scope">
            <el-tag :type="getCertificationStatusType(scope.row.isAuth)">
              {{ getCertificationStatusText(scope.row.isAuth) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialog.type === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="专长" prop="specialty">
          <el-input v-model="form.specialty" type="textarea" placeholder="请输入专长" />
        </el-form-item>
        <el-form-item label="认证状态" prop="isAuth">
          <el-radio-group v-model="form.isAuth">
            <el-radio :label="0">未认证</el-radio>
            <el-radio :label="1">已认证</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDoctorList, addDoctor, updateDoctor, deleteDoctor, certificationDoctor } from '@/api/doctor'

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  name: '',
  deptId: '',
  certificationStatus: ''
})

// 数据列表
const loading = ref(false)
const total = ref(0)
const doctorList = ref([])
const departmentOptions = ref([])

// 表单相关
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'
})

const formRef = ref()
const form = reactive({
  id: undefined,
  username: '',
  password: '',
  realName: '',
  deptId: '',
  title: '',
  specialty: '',
  introduction: '',
  isAuth: 0
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
}

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getDoctorList(queryParams)
    doctorList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}


// 查询操作
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.deptId = ''
  queryParams.certificationStatus = ''
  handleQuery()
}

// 新增操作
const handleAdd = () => {
  dialog.type = 'add'
  dialog.title = '新增医生'
  dialog.visible = true
  resetForm()
}

// 编辑操作
const handleEdit = (row) => {
  dialog.type = 'edit'
  dialog.title = '编辑医生'
  dialog.visible = true
  Object.assign(form, row)
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该医生吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDoctor(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 认证操作
const handleCertification = async (id, status) => {
  try {
    await certificationDoctor(id, status)
    ElMessage.success('操作成功')
    getList()
  } catch (error) {
    console.error('认证操作失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialog.type === 'add') {
          await addDoctor(form)
          ElMessage.success('新增成功')
        } else {
          await updateDoctor(form)
          ElMessage.success('更新成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 弹窗关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

// 认证状态显示
const getCertificationStatusText = (status) => {
  const statusMap = {
    0: '未认证',
    1: '已认证',
    2: '认证失败'
  }
  return statusMap[status] || '未知'
}

const getCertificationStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || ''
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    username: '',
    password: '',
    realName: '',
    deptId: '',
    title: '',
    specialty: '',
    introduction: '',
    isAuth: 0
  })
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
